<template>
  <div class="upload-img">
    <el-upload
      accept="image/png,image/jpeg"
      action="#"
      :on-remove="handleRemove"
      :file-list="fileList"
      list-type="picture-card"
      :class="{ disable: value }"
      :on-preview="handlePreview"
      :http-request="handleUpload"
    >
      <!-- 有头像显示头像 -->
      <!-- <img :src="value" v-if="value" /> -->
      <!-- 无头象显示加号  -->
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="预览" :visible="isShow" />
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";
export default {
  name: "UploadImg",
  data() {
    return {
      isShow: false,
    };
  },

  props: {
    value: {
      type: String,
      default: "",
    },
  },
  computed: {
    fileList: {
      get() {
        return this.value ? [{ name: "", url: this.value }] : [];
      },
      set() {},
    },
  },
  methods: {
    // 文件移除是的钩子
    handleRemove() {
      // 需要吧value清空
      //子传父出发input事件
      this.$emit("input", "");
    },
    handlePreview() {
      this.isShow = true;
    },
    // 上传
    handleUpload({ file }) {
      // 上传到腾讯云服务器
      const cos = new COS({
        SecretId: "AKIDRguxkGWabSEm6D4hW4XsynMhma8Ua2FE",
        SecretKey: "nOinb8artgCajeOCuPfmjSv84jIjxwfv",
      });
      // 调用方法上传
      cos.putObject(
        {
          Bucket: "fan-tong-1317090935", //桶名
          Region: "ap-beijing", //地区
          Key: file.name, //文件名
          Body: file, //文件对想
        },
        (err, data) => {
          if (err) {
            return this.$message.success("上传失败");
          }
          // 拿到地址同步到父组件中
          this.$emit("input", `https://${data.Location}`);
          console.log(data.Location);
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.el-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-upload:hover {
  border-color: #409eff;
}
i {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 100%;
  text-align: center;
}
.disable {
  ::v-deep {
    .el-upload {
      display: none;
    }
  }
}
</style>

